package org.example.fileServer;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.util.ImageApp;

import java.net.InetAddress;
import java.util.Date;

/**
 * @classname: ServerHandler
 * @description: TODO
 * @author: kaiser
 * @date: 2024/3/16 17:44
 * @version: 1.0
 */
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 为新连接发送庆祝
        ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
        ctx.write("It is " + new Date() + " now.\r\n");
        ctx.flush();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
        String[] split = request.split("\\|");
        String value = split[0];
        System.out.println("value:"+ value);
        byte[] bytes = value.getBytes();
        new ImageApp(bytes);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
